package com;  
 /**
  * 简单处理用于 用户与master 方便测试
  */
import java.io.IOException;
import java.util.ArrayList;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;  
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;  
import org.springframework.web.socket.handler.TextWebSocketHandler;  
  
public class WebsocketEndPoint extends TextWebSocketHandler {  
	
	
	
	public static  ArrayList<WebSocketSession> users = new ArrayList<WebSocketSession>();
	
	@Override
	protected void handleTextMessage(WebSocketSession session,
			TextMessage message) throws Exception {
			//简单处理
			System.out.println(session.getId());
			System.out.println("收到消息");
			String user =(String) session.getAttributes().get("user");
			if(user.equals("lb")){
				System.out.println("发送信息到客服端：");
				sendMessageToUser("master",message);//发送给客服的信息
			}
			if(user.equals("master")){
				System.out.println("发送信息到用户端：");
				sendMessageToUser("lb",message);//发送给客服的信息
			}
			super.handleTextMessage(session, message);
	}
	@Override
	public void handleMessage(WebSocketSession session,
			WebSocketMessage<?> message) throws Exception {
		super.handleMessage(session, message);
	}
    public void sendMessageToUsers(TextMessage message){
    	for (WebSocketSession user : users) {
            try {
                if (user.isOpen()) {
                    user.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
	public void sendMessageToUser(String userName,TextMessage message){
		for (WebSocketSession user : users) {
            if (user.getAttributes().get("user").equals(userName)) {
                try {
                    if (user.isOpen()) {
                        user.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
	}
	@Override
	public void afterConnectionEstablished(WebSocketSession session)
			throws Exception {
		super.afterConnectionEstablished(session);
		System.out.println("连接成功，保存SESSION");
        users.add(session);
        String userName = (String) session.getAttributes().get("123");
        if(userName!= null){
            session.sendMessage(new TextMessage(21313 + "条未读信息"));
        }
	}
	
	@Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		System.out.println("连接关闭，删除连接SESSION");
        users.remove(session);
    }
	
	@Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if(session.isOpen()){
            session.close();
        }
        System.out.println("连接出错，关闭session,删除连接SESSION......");
        users.remove(session);
    }
		
} 